/*
 * @Author: 赵宇
 * @Description:
 * @Date: 2024-01-28 22:20:21
 * @LastEditTime: 2025-02-17 22:28:31
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \dance\static\js\fn.js
 */
import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
import weekday from '@/common/js/weekday.js';
import { shareList } from '@/common/js/global';
dayjs.extend(weekday);
let _uni = uni;
// 返回上一页，但是这里增加了，如果没有上一页，就直接返回到首页
const onLeft = () => {
  let page = _uni.$uv.pages();
  if (page.length === 1) {
    _uni.$uv.route({
      type: 'switchTab',
      url: '/pages/index/index3'
    });
    return;
  }
  _uni.$uv.route({
    type: 'back'
  });
};
const onHome = () => {
  _uni.$uv.route({
    type: 'switchTab',
    url: '/pages/index/index3'
  });
};
const isLogin = () => {
  const value = _uni.getStorageSync('login');
  if (!value) {
    return true;
  }
  return false;
};
const login = async code => {
  return await _uni.$uv.http.post('app/wechat/jscode2session', { code });
};
const compressFn = file => {
  return new Promise(async (resolve, reject) => {
    let type = isFileType(file);
    // 如果是图片
    if (type === 'image') {
      _uni.compressImage({
        src: file,
        quality: 80,
        success: res => {
          resolve(res.tempFilePath);
        },
        fail: err => {
          // 压缩失败，失败了就不压缩了，直接上传。
          resolve(file);
        }
      });
    } else if (type === 'video') {
      // 视频不压缩了，视频上传之后糊的不行，压的很垃圾
      // _uni.compressVideo({
      //   src: file,
      //   quality: 'low',
      //   success: res => {
      //     resolve(res.tempFilePath);
      //   },
      //   fail: err => {
      //     // 压缩失败，失败了就不压缩了，直接原视频上传。
      //     resolve(file);
      //   }
      // });
      resolve(file);
    } else {
      resolve(file);
    }
  });
};
// 上传文件 上传组件压缩的太夸张了 compressed 选项 7M的视频 如果用了compressed之后，直接压缩成了0.7m  如果采用 compressVideo 7m的视频还有 4m ，所以这里采用了接口压缩.
const uploadFn = (file, isCompress = true) => {
  return new Promise(async (resolve, reject) => {
    if (!file) {
      return;
    }
    if (isCompress) {
      file = await compressFn(file);
    }
    let lastIndex = file.lastIndexOf('.');
    let extName = lastIndex > -1 ? file.slice(lastIndex + 1) : '';
    let opt = await _uni.$uv.http.get(`sdk/tencent/get_policy?ext=${extName}`);
    // 对更多字符编码的 url encode 格式
    let camSafeUrlEncode = function (str) {
      return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
    };

    let formData = {
      key: opt.cosKey,
      policy: opt.policy, // 这个传 policy 的 base64 字符串
      success_action_status: 200,
      'q-sign-algorithm': opt.qSignAlgorithm,
      'q-ak': opt.qAk,
      'q-key-time': opt.qKeyTime,
      'q-signature': opt.qSignature
    };
    // 如果服务端用了临时密钥计算，需要传 x-cos-security-token
    if (opt.securityToken) formData['x-cos-security-token'] = opt.securityToken;
    _uni.uploadFile({
      url: 'https://' + opt.cosHost, //仅为示例，非真实的接口地址
      filePath: file,
      name: 'file',
      formData: formData,
      success: res => {
        if (![200, 204].includes(res.statusCode)) {
          _uni.$uv.toast('上传失败!');
          reject('上传失败');
        }
        resolve('https://' + opt.cosHost + '/' + camSafeUrlEncode(opt.cosKey).replace(/%2F/g, '/'));
      },
      error(err) {
        reject('上传失败');
      }
    });
  });
};
// 判断当前url是什么文件
function isFileType(url) {
  const imageRegex = /\.(jpg|jpeg|png|gif|bmp|svg)$/i;
  const videoRegex = /\.(mp4|webm|ogg|mkv|avi|wmv|MP4)$/i;
  const mp3Regex = /\.(mp3|MP3|m4a|M4A)$/i;

  if (imageRegex.test(url)) {
    return 'image';
  } else if (videoRegex.test(url)) {
    return 'video';
  } else if (mp3Regex.test(url)) {
    return 'mp3';
  } else {
    return 'unknown';
  }
}

function getPercentage(percentage) {
  var num;
  switch (percentage) {
    case 1:
      num = 10;
      break;
    case 2:
      num = 30;
      break;
    case 3:
      num = 60;
      break;
    case 4:
      num = 80;
      break;
    default:
      num = 100;
  }
  return num;
}

function getGradeStr(grade) {
  var str;
  switch (grade) {
    case 1:
      str = '纯纯新人';
      break;
    case 2:
      str = '进阶新手';
      break;
    case 3:
      str = '小有所成';
      break;
    case 4:
      str = '展露头角';
      break;
    default:
      str = '百炼成钢';
  }
  return str;
}

function getGradeToWho(grade) {
  var str;
  switch (grade) {
    case 1:
      str = '刚刚接触舞蹈的新人，想练好基本功，跳出好看的动作';
      break;
    case 2:
      str = '近期舞蹈系统学习超过28课时以上，有一定记动作能力';
      break;
    case 3:
      str = '近期舞蹈系统学习超过64课时以上，有一定的基础动作基础，能记住老师课堂上教授的动作';
      break;
    case 4:
      str = '有相当舞蹈学习的基础，能顺利记住老师课堂教授动作，追求自己的风格';
      break;
    default:
      str = '你都这水平了，不用我写了吧';
  }
  return str;
}

function getGradeIntroduce(grade) {
  var str;
  switch (grade) {
    case 1:
      str = '完成28节入门课程，打下坚实基础。';
      break;
    case 2:
      str = '通过36节课程，深化技能，挑战新动作。';
      break;
    case 3:
      str = '累计48节，熟练掌握舞蹈组合，展现个性。';
      break;
    case 4:
      str = '再学96节，面对高级挑战，提升技艺。';
      break;
    default:
      str = '完成所有阶段，技艺精湛，表演自如。';
  }
  return str;
}
// 是不是没日期，或者日期是 0001 都当没日期
const isTimeNull = str => {
  return !str || str.includes('0001-01-01');
};
// 获取周几的方法
const getWeek = val => {
  const str = isTimeNull(val) ? `` : '周' + ['日', '一', '二', '三', '四', '五', '六'][dayjs(val).weekday()];
  return str;
};
// 提醒
const toastFn = (ref, message, type = 'error', overlay = false) => {
  if (ref) {
    ref.show({ overlay, message, type });
  } else {
    _uni.showToast({
      title: message,
      duration: 2000,
      icon: type
    });
  }
};
const suiji = (min = 0, max = 99999999999999999) => {
  const min1 = min;
  const max1 = max;
  return new Promise((resolve, reject) => {
    // #ifdef H5
    resolve(_uni.$uv.random(min, max));
    // #endif
    // #ifdef MP-WEIXIN
    // 如果是从朋友圈来的，直接返回0就好了。因为限制太多了。
    if(_uni.getLaunchOptionsSync().scene === 1154) {
      resolve(0);
      return
    }
    wx.getRandomValues({
      length: 4, // 生成 4 个字节长度的随机数,
      success: res => {
        const randomBytes = new Uint8Array(res.randomValues);
        const randomBytes32 = new Uint32Array(randomBytes.buffer);
        const result = randomBytes32[0] / Math.pow(2, 32);
        const min2 = Math.ceil(min1);
        const max2 = Math.floor(max1);
        const num = Math.floor(result * (max2 - min2)) + min2;
        resolve(num);
      },
      fail: err => {
        reject(err);
      }
    });
    // #endif
  });
};
const shareTimeline = async () => {
  let pages = _uni.$uv.pages();
  let url = pages[pages.length - 1]?.$page?.fullPath || '';
  const { miniProgram } = _uni.getAccountInfoSync();
  let { envVersion } = miniProgram;
  let random = await suiji(0, shareList.length - 1);
  let title = (envVersion === 'release' ? '' : '测试') + '去卡' + shareList[random].name;
  title += `#快来一起跳舞吧~`;
  return {
    title,
    query: `${url.split('?')[1]}&isSharePyq=1`
  };
};
// 前往老师页面
const onGoTeacher = id => {
  if (!id) return;
  _uni.$uv.route({
    url: '/pages/me/share',
    params: {
      id
    }
  });
};
// 前往视频页面
const onGoVideo = id => {
  if (!id) return;
  _uni.$uv.route({
    url: '/pages/teacher/videoPreview',
    params: {
      id
    }
  });
};
export {
  onLeft,
  onHome,
  isLogin,
  login,
  uploadFn,
  isFileType,
  getPercentage,
  getGradeStr,
  getGradeToWho,
  getGradeIntroduce,
  isTimeNull,
  getWeek,
  toastFn,
  shareTimeline,
  onGoTeacher,
  onGoVideo,
  suiji
};
